import React, {useEffect, useState} from 'react';
import {DrawerForm, PageContainer, ProField, ProFormSelect, ProFormText} from "@ant-design/pro-components";
import {Button, Card, Descriptions, Empty, Form, Input, List, message, Modal, Popconfirm, Table, Tabs, Tag} from 'antd';
import {DeleteOutlined, EditOutlined, FontSizeOutlined, PlusOutlined} from '@ant-design/icons';
import {
  addTableUsingPost,
  deleteTableUsingDelete,
  listTableUsingPost,
  updateTableUsingPut
} from "@/services/backend/tablesController";
import dayjs from "dayjs";
import {useModel} from "@@/exports";
import {listFieldUsingGet} from "@/services/backend/fieldsController";

const tabList = [
  {
    key: 'all',
    label: '全部',
  },
  {
    key: 'my',
    label: '私有的',
  },
  {
    key: 'public',
    label: '公开的',
  },
];

const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [list, setList] = useState<Array<API.Tables>>([]);
  const [fieldsList, setFieldsList] = useState<Array<API.Fields>>([]);
  const [drawerOpen, setDrawerOpen] = useState<boolean>(false);
  const [isModalOpen, setModalOpen] = useState<boolean>(false);
  const [updateDrawerOpen, setUpdateDrawerOpen] = useState<boolean>(false);
  const [oldFormValue] = Form.useForm<API.TablesUpdateDto>()
  const [query, setQuery] = useState<API.TablesListDto>({
    tablesComment: "",
    tablesType: undefined
  });
  const { currentUser } = initialState || {};

  const getList = async () => {
    const { data } = await listTableUsingPost({
      ...query
    });
    setList(data || []);
  };

  const search = (value : string) => {
    setQuery({
      ...query,
      tablesComment: value,
    });
  };

  const tabChange = (key: string) => {
    if (key === 'all') {
      setQuery({
        ...query,
        tablesType: undefined
      });
      return;
    }
    setQuery({
      ...query,
      tablesType: key === 'public' ? 1 : 0
    });
  };

  const openDrawerOpen = () => {
    setDrawerOpen(true);
  }

  const addTable = async (value: any) => {
    const {code} = await addTableUsingPost({
      tablesComment: value.tablesComment,
      tablesName: value.tablesName,
      tablesTag: value.tablesTag,
      tablesType: value.tablesType
    })
    if (code === 0){
      message.success('创建成功')
      getList()
      setDrawerOpen(false);
    }
  }

  const updateTable = async (value: API.TablesUpdateDto) => {
    const {code} = await updateTableUsingPut({
      ...value
    })
    if (code === 0){
      message.success('更新成功')
      getList()
      setUpdateDrawerOpen(false);
    }
  }

  useEffect(() => {
    getList();
  }, [query]);

  const columns = [
    {
      title: '字段名',
      dataIndex: 'field',
    },
    {
      title: '字段类型',
      dataIndex: 'fieldsType',
    },
    {
      title: '是否允许为空',
      dataIndex: 'fieldsIsNull',
      render: (text: string, record: API.Fields) => {
        return (
          <Tag
            color={record.fieldsIsNull === 0 ? 'success' : 'error'}
          >
            {record.fieldsIsNull === 0 ? '是' : '否'}
          </Tag>
        )
      },
    },
    {
      title: '主键',
      dataIndex: 'fieldsKey',
      render: (text: string, record: API.Fields) => {
        return (
          <Tag
            color={record.fieldsIsNull === 0 ? 'warning' : 'processing'}
          >
            {record.fieldsKey === 1 ? '是' : '否'}
          </Tag>
        )
      },
    },
    {
      title: '默认值',
      dataIndex: 'fieldsDefault',
    },
    {
      title: '附加值',
      dataIndex: 'fieldsExtra',
    },
    {
      title: '字段注释',
      dataIndex: 'fieldsComment',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (text: string, record: API.Fields) => {
        return (
          dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')
        )
      }
    },

  ]

  return (
    <PageContainer
      content={
        <div
          style={{
            padding: 24,
          }}
        >
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              gap: 8,
            }}
          >
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                gap: 4,
              }}
            >
              <Input.Search
                placeholder="请输入"
                enterButton="搜索"
                style={{ maxWidth: 522, width: '100%' }}
                onSearch={value => {
                  search(value)
                }
              }
              />
              <Button
                type={'primary'}
                icon={<PlusOutlined />}
                onClick={openDrawerOpen}
              >
                创建数据库表
              </Button>
            </div>
            <Tabs
              items={tabList}
              onTabClick={tabChange}
            />
          </div>
        </div>
      }
    >
      <>
        { list.length === 0 ?
          <Empty /> :
          <List
            rowKey="id"
            grid={{
              gutter: 16,
              xs: 1,
              sm: 2,
              md: 2,
              lg: 3,
              xl: 3,
              xxl: 3,
            }}
            dataSource={list}
            renderItem={(item) => (
              <List.Item >
                <Card
                  hoverable
                  actions={[
                    <div key="fields">
                      <div onClick={async ()=> {
                        const {code,data} = await listFieldUsingGet({
                          tableId: item.id as string
                        })
                        if (code === 0){
                          setFieldsList(data || [])
                        }
                        setModalOpen(true)
                      }}>
                        <FontSizeOutlined /> 字段
                      </div>

                    </div>,
                    <div key="edit">
                      <div
                        onClick={async ()=> {
                          if (currentUser?.userName !== item.createBy){
                            message.error('只能编辑自己创建的数据表')
                            return false
                          }
                          oldFormValue.setFieldsValue(item)
                          console.log(oldFormValue.getFieldValue)
                          setUpdateDrawerOpen(true)
                        }}
                      >
                        <EditOutlined /> 编辑
                      </div>
                    </div>,
                    <div key="delete">
                      <Popconfirm
                        title="你确定要删除这个数据表吗？"
                        description="数据库表将与所关联字段一同删除，将无法找回"
                        onConfirm={async ()=> {
                          if (currentUser?.userName !== item.createBy){
                            message.error('只能删除自己创建的数据表')
                            return false
                          }
                          const {code} = await deleteTableUsingDelete({
                            id: item.id
                          })
                          if (code === 0){
                            message.success('删除成功')
                            getList()
                          }
                        }}
                        onCancel={()=> {
                          return false
                        }}
                        okText="确定删除"
                        cancelText="取消"
                      >
                          <DeleteOutlined/> 删除
                      </Popconfirm>
                    </div>
                  ]}
                >
                  <Card.Meta  title={item.tablesComment} />
                  <div>
                    <div style={{marginBottom: 24}} />
                    <Descriptions column={2} size={"middle"}>
                      <Descriptions.Item label="表名">{item.tablesName}</Descriptions.Item>
                      <Descriptions.Item label="标签">
                        <Tag color="processing">{item.tablesTag}</Tag>
                      </Descriptions.Item>
                      <Descriptions.Item label="类型">
                        {
                          item.tablesType === 0 ?
                            <Tag color="warning">私有</Tag>
                            : <Tag color="success">公开</Tag>
                        }
                      </Descriptions.Item>
                      <Descriptions.Item label="创建人">{item.createBy}</Descriptions.Item>
                      <Descriptions.Item label="创建时间">
                        <ProField
                          text={dayjs(item.createTime).valueOf()}
                          valueType="dateTime"
                          mode={"read"}
                        />
                      </Descriptions.Item>
                    </Descriptions>
                  </div>
                </Card>
              </List.Item>
            )}
          />
        }
        <DrawerForm<API.TablesAddDto>
          title="新建数据库表"
          resize={{
            maxWidth: window.innerWidth * 0.8,
            minWidth: 600,
          }}
          visible={ drawerOpen }
          autoFocusFirstInput
          drawerProps={{
            destroyOnClose: true,
            placement: 'left'
          }}
          onOpenChange={(open)=>{
              setDrawerOpen(open)
          }}
          onFinish={async (value) => {
            addTable(value)
          }}
        >
          <div>
              <ProFormText
                name='tablesName'
                label="表名"
                placeholder='请输入表名'
                rules={[
                  { required: true, message: '请输入表名' }
                ]}
              />

              <ProFormText
                name='tablesComment'
                label="表注释"
                placeholder='请输入表注释'
                rules={[
                  { required: true, message: '请输入表注释' }
                ]}
              />

              <ProFormText
                name='tablesTag'
                label="表标签"
                placeholder='请输入表标签'
                rules={[
                  { required: true, message: '请输入表标签' }
                ]}
              />

              <ProFormSelect
                name="tablesType"
                label="数据表类型"
                options={[
                  { label: '私有', value: 0 },
                  { label: '公开', value: 1 },
                ]}
                placeholder="请选择数据表类型"
                rules={[
                  { required: true, message: '请选择数据表类型' }
                ]}
              />
          </div>
        </DrawerForm>
        <DrawerForm<API.TablesUpdateDto>
          title="修改数据库表"
          resize={{
            maxWidth: window.innerWidth * 0.8,
            minWidth: 600,
          }}
          visible={ updateDrawerOpen }
          autoFocusFirstInput
          drawerProps={{
            destroyOnClose: true,
            placement: 'left'
          }}
          form={oldFormValue}
          onOpenChange={(open)=>{
            setUpdateDrawerOpen(open)
          }}
          onFinish={async (value) => {
            updateTable(value)
          }}
        >
          <div>
            <ProFormText
              name='id'
              hidden={true}
            />

            <ProFormText
              name='tablesName'
              label="表名"
              placeholder='请输入表名'
              rules={[
                { required: true, message: '请输入表名' }
              ]}
            />

            <ProFormText
              name='tablesComment'
              label="表注释"
              placeholder='请输入表注释'
              rules={[
                { required: true, message: '请输入表注释' }
              ]}
            />

            <ProFormText
              name='tablesTag'
              label="表标签"
              placeholder='请输入表标签'
              rules={[
                { required: true, message: '请输入表标签' }
              ]}
            />

            <ProFormSelect
              name="tablesType"
              label="数据表类型"
              options={[
                { label: '私有', value: 0 },
                { label: '公开', value: 1 },
              ]}
              placeholder="请选择数据表类型"
              rules={[
                { required: true, message: '请选择数据表类型' }
              ]}
            />
          </div>
        </DrawerForm>
        <Modal
          title="查看数据库表字段"
          open={isModalOpen}
          width={1000}
          onCancel={() => {
            setModalOpen(false)
          }}
          onOk={() => {
            setModalOpen(false)
          }}
        >
          {
            fieldsList.length === 0 ?
              <Empty />
              :
              <Table
                pagination={false}
                rowKey="id"
                dataSource={fieldsList}
                columns={columns}
              />
          }
        </Modal>
      </>
    </PageContainer>
  )
}

export default TableList;
